<template>
  <div>
    <div class="box">
      <div class="button">
        <div class="button_left">
          <el-button type="primary" :icon="Plus" @click="addUp()"
            >添加</el-button
          >
        </div>
        <div class="button_reght">
          <el-button plain :icon="Grid" />
          <el-button plain :icon="Search" />
        </div>
      </div>
      <div class="science_list">
        <el-table
          :data="
            scenicList.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" fixed />
          <el-table-column label="商品ID" width="100" fixed>
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.id }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="120" fixed>
            <template #default="scope">
              <!-- <el-popover effect="light" placement="top" width="auto"> -->
              <!-- <template #default>
                <div>name: {{ scope.row.name }}</div>
              </template> -->

              <div style="display: flex; align-items: center">
                <span>{{ scope.row.name }}</span>
              </div>

              <!-- </el-popover> -->
            </template>
          </el-table-column>
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <img
                  :src="'https://c2c.kuxia.top' + scope.row.img"
                  alt=""
                  style="width: 50px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.price }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.stock }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品介绍" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <div v-html="scope.row.introduce" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品轮播" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <img
                  :src="'https://c2c.kuxia.top' + scope.row.banner"
                  alt=""
                  style="width: 50px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类名称" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.tname }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类ID" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.tid }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="首页推荐" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.status == 0 ? "否" : "是" }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination
          :align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="scenicList.length"
        />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="newlyIncreased"
      :title="status == -1 ? '新增' : '编辑'"
      :before-close="handleClose"
    >
      <el-scrollbar height="400px">
        <el-form :model="addition" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="addition.name"
              autocomplete="off"
              placeholder="请输入商品名称"
              style="width: 90%"
            />
          </el-form-item>
          <el-form-item
            label="商品图片"
            :label-width="formLabelWidth"
            style=""
            prop="img"
          >
            <el-input
              v-model="addition.img"
              placeholder="请上传图片"
              class="input-with-select"
              readonly="true"
              style="width: 90%"
            />
          </el-form-item>
          <div style="margin-left: 20%; padding-right: 8%">
            <el-upload
              ref="upload"
              v-model:file-list="fileList"
              class="upload-demo"
              action="https://scienicpc.kuxia.top/pcapi/File/fileimg"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleUpchange"
              :auto-upload="false"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="success" :icon="Upload">上传</el-button>
              <el-button type="primary" :icon="Operation" @click="submitUpload"
                >选择</el-button
              >
            </el-upload>
          </div>
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="tid"
          >
            <el-select
              v-model="addition.tid"
              value-key="id"
              placeholder="请选择类型"
              style="width: 90%"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品价格"
            :label-width="formLabelWidth"
            prop="price"
          >
            <el-input
              v-model="addition.price"
              style="width: 90%"
              placeholder="请输入价格"
              type="number"
            />
          </el-form-item>
          <el-form-item
            label="商品库存"
            :label-width="formLabelWidth"
            prop="stock"
          >
            <el-input
              v-model="addition.stock"
              style="width: 90%"
              placeholder="请输入数量"
              type="number"
            />
          </el-form-item>
          <el-form-item
            label="商品介绍"
            :label-width="formLabelWidth"
            prop="introduce"
          >
            <div style="border: 1px solid #ccc; width: 90%">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 200px; overflow-y: hidden"
                v-model="addition.introduce"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
          <el-form-item
            label="商品轮播"
            :label-width="formLabelWidth"
            style="flex-wrap: wrap"
            prop="banner"
          >
            <div style="width: 90%">
              <el-upload
                v-model:file-list="fileBanner"
                class="upload-demo"
                action="https://c2c.kuxia.top/pcapi/index/upload"
                :on-preview="handlePreviewBanner"
                :on-remove="handleRemoveBanner"
                :on-change="handleUpchangeBanner"
                list-type="picture"
                :limit="4"
                :auto-upload="false"
              >
                <el-button type="primary">上传轮播图</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    轮播图最少上传一张最多上传4张
                  </div>
                </template>
              </el-upload>
            </div>
            <el-input
              v-model="addition.banner"
              placeholder="请上传图片"
              class="input-with-select"
              readonly="true"
              style="width: 90%; display: none"
            />
          </el-form-item>
          <el-form-item
            label="首页推荐"
            :label-width="formLabelWidth"
            prop="status"
          >
            <el-select
              v-model="addition.status"
              value-key="id"
              placeholder="请选择是否推荐"
              style="width: 90%"
            >
              <el-option
                v-for="item in recommend"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addScenic(ruleFormRef)">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
            v-if="status == -1"
          >
            新增
          </el-button>
          <el-button
            type="primary"
            @click="submitFormRedact(ruleFormRef)"
            v-else
          >
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { reactive } from "vue";
import {
  Plus,
  Delete,
  Search,
  Grid,
  Upload,
  Operation
} from "@element-plus/icons-vue";
// import { CountTo } from "vue3-count-to";
import {
  goodsIndex,
  imageUpload,
  goodsAdd,
  goodsDeletes,
  goodsEdits,
  typeList
} from "@/api/index";
// import packpage from "../../../package.json";
// import { useI18n } from "vue-i18n";
// import { getResouceList } from "@/api/index";

// import { useStore } from "vuex";
// import axios from "axios";
import { genFileId, ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { useUser } from "@/pinia/index";
const user = useUser();
console.log(user.list);

// const components = ref({
//   Editor,
//   Toolbar
// });
const mode = ref("default");
const currentPage = ref(1);
const pageSize = ref(5);
const scenicList = ref([]);
const newlyIncreased = ref(false);
const status = ref();
const options = ref([]);
const formLabelWidth = "140px";
const addition = reactive({
  name: "",
  img: "",
  tid: "",
  price: "",
  stock: "",
  banner: "",
  introduce: "",
  status: ""
});
const loading = ref(true);
const recommend = ref([
  {
    name: "是",
    id: 1
  },
  {
    name: "否",
    id: 0
  }
]);
const fileList = ref<UploadUserFile[]>([]);
const fileBanner = ref<UploadUserFile[]>([]);
const addUp = () => {
  status.value = -1;
  newlyIncreased.value = true;
  addition.name = "";
  addition.img = "";
  addition.tid = "";
  addition.price = "";
  addition.stock = "";
  addition.banner = "";
  addition.introduce = "";
  fileList.value.length = 0;
};
const upload = ref();
const handleExceed = files => {
  console.log(files);
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
const handleRemove = () => {
  console.log(123);
  console.log(addition.img);
  addition.img = "";
};
const handleRemoveBanner: UploadProps["onRemove"] = (
  uploadFile,
  uploadFiles
) => {
  console.log(uploadFile, uploadFiles);
};
const handlePreviewBanner: UploadProps["onPreview"] = file => {
  console.log(file);
};
const submitUpload = () => {
  upload.value.submit();
};
const id = ref();
function output() {
  console.log(addition.status);
}
const ruleFormRef = ref();
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "blur"
    }
  ],
  img: [
    {
      required: true,
      message: "请上传图片",
      trigger: "change"
    }
  ],
  tid: [
    {
      required: true,
      message: "请选择类型",
      trigger: "change"
    }
  ],
  price: [
    {
      required: true,
      message: "请输入商品价格",
      trigger: "change"
    }
  ],
  stock: [
    {
      required: true,
      message: "请输入商品库存",
      trigger: "change"
    }
  ],
  banner: [
    {
      required: true,
      message: "请上传轮播图",
      trigger: "change"
    }
  ],
  introduce: [
    {
      required: true,
      message: "请输入商品介绍",
      trigger: "change"
    }
  ],
  status: [
    {
      required: true,
      message: "请选择是否推荐",
      trigger: "change"
    }
  ]
});
typeList().then(res => {
  console.log(res);
  options.value = res.data.data;
});
const handleUpchange = uploadFile => {
  console.log(uploadFile);
  const param = new FormData(); //创建form对象
  param.append("file", uploadFile.raw, uploadFile.raw.name); //通过append向form对象添加数据
  console.log(param);

  imageUpload(param).then(res => {
    console.log(res);
    addition.img = "" + res.data.url;
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const handleUpchangeBanner = uploadFile => {
  console.log(uploadFile);
  const param = new FormData(); //创建form对象
  param.append("file", uploadFile.raw, uploadFile.raw.name); //通过append向form对象添加数据
  console.log(param);
  if (fileBanner.value.length >= 3) {
    ElMessage({
      message: "最多上传4张图片",
      type: "error"
    });
    return;
  }
  if (addition.banner) {
    addition.banner += ",";
  }
  imageUpload(param).then(res => {
    console.log(res);
    addition.banner += "" + res.data.url;
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const submitForm = async formEl => {
  console.log(!formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(addition);
      //商品添加
      goodsAdd(addition).then(res => {
        console.log(res);
        newlyIncreased.value = false;
        goodsIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//商品编辑
const submitFormRedact = async formEl => {
  // newlyIncreased.value = false;
  console.log(!formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(addition);
      goodsEdits({
        ...addition,
        id: status.value
      }).then(res => {
        console.log(res); // 成功回调
        newlyIncreased.value = false;
        goodsIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
function addScenic(formEl) {
  newlyIncreased.value = false;
  if (!formEl) return;
  formEl.resetFields();
}
//请求列表信息
if (user.list.length) {
  loading.value = false;
  scenicList.value = user.list;
} else {
  user.getList().then(res => {
    loading.value = false;
    console.log(res);
    scenicList.value = res;
  });
}
//每页条数改变时触发 选择一页显示多少行
function handleSizeChange(val) {
  console.log(`每页 ${val} 条`);
  currentPage.value = 1;
  pageSize.value = val;
}
//当前页改变时触发 跳转其他页
function handleCurrentChange(val) {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
}

function handleEdit(index, arr) {
  status.value = arr.id;
  goodsIndex({ id: arr.id }).then(res => {
    console.log(res);
    if (res.data.code == 0) {
      ElMessage.error(res.data.err);
    } else {
      fileList.value.length = 0;
      fileBanner.value.length = 0;
      newlyIncreased.value = true;
      addition.name = res.data.data[0].name;
      addition.img = res.data.data[0].img;
      addition.tid = res.data.data[0].tid;
      addition.price = res.data.data[0].price;
      addition.stock = res.data.data[0].stock;
      addition.banner = res.data.data[0].banner;
      addition.introduce = res.data.data[0].introduce;
      addition.status = res.data.data[0].status;
      const str = {
        url: "https://c2c.kuxia.top" + res.data.data[0].img
      };
      fileList.value.push(str);
      for (let i = 0; i < res.data.data[0].banners.length; i++) {
        const strs = {
          url: res.data.data[0].banners[i]
        };
        fileBanner.value.push(strs);
      }

      console.log(addition);
    }
  });
}

function handleDelete(index, arr) {
  console.log(index);
  console.log(arr);
  goodsDeletes({ id: arr.id }).then(res => {
    console.log(res); // 成功回调
    goodsIndex().then(res => {
      scenicList.value = res.data.data;
    });
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    addition.introduce = "<p></p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped>
.box {
  background-color: white;
  padding: 20px;
}
.button {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.paging {
  width: 100%;
  text-align: center;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
